package com.voodoo.lib_frame.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.voodoo.lib_frame.Config;
import com.voodoo.lib_frame.R;
import com.voodoo.lib_frame.receiver.NetBroadcastReceiver;
import com.voodoo.lib_frame.tip.XToastUtils;

import java.io.File;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Author: voodoo
 * CreateDate: 2019/08/29 029 下午 12:30:02
 * Description: 所有Fragment的基类
 */
public abstract class BaseFragment extends Fragment implements BaseView, NetBroadcastReceiver.NetEvent {

    private Unbinder unbinder;
    private ProgressDialog progressDialog;
    private Context context;
    private Toast toast;

    private boolean isShowProgress;

    /**
     * Fragment与Activity绑定完成的时候执行的生命周期
     *
     * @param context 被绑定的Activity的Context
     */
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    /**
     * 获取当前Fragment绑定的Context
     *
     * @return Context
     */
    public Context getFragmentContext() {
        return this.context;
    }

    /**
     * 初始化创建Fragment生命周期
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_base, container, false);
        rootView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
        FrameLayout content = rootView.findViewById(R.id.baseActivity_content_flayout);
        View view = inflater.inflate(getLayoutResId(), null);
        content.addView(view);


        if (Config.isShowRootTitle) {
            TextView rootText = new TextView(getActivity());
            rootText.setText(new StringBuffer().append("Fragment:").append(" --> ").append(getClass().getSimpleName()));
            rootText.setTextColor(Color.parseColor("#0030F0"));
            content.addView(rootText);
        }

        unbinder = ButterKnife.bind(this, view);
        initViews(view);
        initProgressDialog();

        return rootView;
    }

    private void initProgressDialog() {
        // 初始化progressDialog，设置样式
        progressDialog = new ProgressDialog(getActivity(), R.style.loading_dialog);
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);// 点击返回消失
        progressDialog.setCanceledOnTouchOutside(false);// 点击外部消失
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    protected abstract int getLayoutResId();

    protected abstract void initViews(View view);

    protected abstract void initData();

    // ================================== View的点击事件和长按事件 ==================================

    /**
     * View的点击事件
     *
     * @param view 被点击的View
     */
    public void onClick(View view) {
    }

    /**
     * View的长按事件
     *
     * @param view 被长按的View
     */
    public void onLongClick(View view) {
    }

    // ========================================= 页面跳转 ==========================================

    /**
     * 界面跳转
     *
     * @param cls    跳转的目标界面
     * @param bundle 传参，若不传参则设置为null
     */
    protected void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(getFragmentContext(), cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 带返回值的特面条转
     *
     * @param cls         目标界面
     * @param bundle      传参，若不传参则设置为null
     * @param requestCode 请求码
     */
    protected void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent(getFragmentContext(), cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    // ======================================== Toast和提示 ========================================

    /**
     * 展示Toast提示
     *
     * @param msg 展示的消息
     */
    public void showToast(String msg) {
        if (toast != null) {
            toast.cancel();
        }
        toast = Toast.makeText(getFragmentContext(), msg, Toast.LENGTH_SHORT);
        toast.show();
    }

    /**
     * 展示带图标的Toast（一般推荐用于服务器返回的提示）
     *
     * @param tipBitmap 资源图标
     * @param tips      提示消息
     */
    protected void showTip(int tipBitmap, String tips) {
        XToastUtils.getInstance().toShowXToast( getActivity(), tips,tipBitmap ,3000);
    }

    /**
     * 正确提示
     *
     * @param tips 提示内容
     */
    protected void showRightTip(String tips) {
        showTip(R.drawable.icon_right_tip, tips);
    }

    /**
     * 错误提示
     *
     * @param tips 提示内容
     */
    protected void showErrorTip(String tips) {
        showTip(R.drawable.icon_error_tip, tips);
    }

    /**
     * 显示加载框（转圈的那个）
     *
     * @param loadingStr 提示的文字
     */
    protected void showProgressDialog(String loadingStr) {
        isShowProgress = true;
        if (!progressDialog.isShowing() && !getActivity().isFinishing()) {
            progressDialog.show();
            View views = LayoutInflater.from(getActivity()).inflate(R.layout.view_loading_dialog, null);
            TextView loading_tv_content = views.findViewById(R.id.loading_tv_content);
            loading_tv_content.setText(loadingStr);
            progressDialog.setContentView(views);
        }
    }

    /**
     * 移除掉先前展示的那个加载框
     */
    protected void removeProgressDialog() {
        if (isShowProgress) {
            isShowProgress = false;
            if (getActivity() != null && !getActivity().isFinishing()) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }
        }
    }

    // ============================================ API ============================================

    @Override
    public void onStarted(String loadingStr) {
        showProgressDialog(loadingStr);
    }

    @Override
    public void onLoading(long total, long current) {
    }

    @Override
    public void onComplete() {
        removeProgressDialog();
    }

    @Override
    public void onErrorTip(String errorStr) {
        showErrorTip(errorStr);
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {

    }

    @Override
    public void onError(String requestUrl, String errorMsg, String data) {

    }

    @Override
    public void onNetChange(int netMobile, boolean isConnect) {

    }

    @Override
    public void onFailure(String requestUrl, String requestMsg) {
    }

    @Override
    public void onException(Exception exception) {
    }

    @Override
    public void onDownloadFailed(String requestUrl, Exception e) {

    }

    @Override
    public void onDownloadSuccess(String requestUrl, File file) {

    }

    @Override
    public void onDownloading(String requestUrl, long total, long progress) {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind(); // 销毁界面的时候解绑
    }

    @Override
    public void onStop() {
        super.onStop();
    }

}
